package com.cps.match.connection;

import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import com.cps.match.service.impl.ConfigurationApp;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthUtil;

public class SecurityHolder {
	static String privateKeyFile =ConfigurationApp.getKey("sec.privatekey.file");
	static String privateKeyPass=ConfigurationApp.getKey("sec.privatekey.password");
	static String privateKeyAlias = ConfigurationApp.getKey("sec.privatekey.alias");
	static String privateKeyType =ConfigurationApp.getKey("sec.privatekey.type");
	static String privateConsumerKey=ConfigurationApp.getKey("sec.app.consumerkey");

	private static SecurityHolder instance = new SecurityHolder();

	private SecurityHolder() {
	}

	public static PrivateKey getPrivateKey() throws IOException{
		try{
			return instance.loadPrivateKey();
		}catch(Exception ex) {
			throw new IOException("Load private key failed.", ex);
		}
		
	}

	protected PrivateKey loadPrivateKey() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
		String kspw = privateKeyPass;
		String privKeyFile = privateKeyFile;
		String keyAlias = privateKeyAlias;

		KeyStore ks = KeyStore.getInstance(privateKeyType);

		// get user password and file input stream
		ClassLoader cl = this.getClass().getClassLoader();
		InputStream stream = cl.getResourceAsStream(privKeyFile);

		ks.load(stream, kspw.toCharArray());
		Key key = ks.getKey(keyAlias, kspw.toCharArray());
		return (PrivateKey) key;

	}
	
	public static OAuthParameters getDefaultOAuthParam() {
		OAuthParameters params = new OAuthParameters();
		params.setOAuthConsumerKey(privateConsumerKey);
		params.setOAuthNonce(OAuthUtil.getNonce());
		params.setOAuthTimestamp(OAuthUtil.getTimestamp());
		params.setOAuthSignatureMethod("RSA-SHA1");
		params.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH);
		params.addCustomBaseParameter("oauth_version", "1.0");
		return params;
	}

}
